﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Configuration;
using Users;

namespace WanPiJie.Accounts
{
	/// <summary>
	/// 用户登录验证Module
	/// </summary>
	public class LoginModule : IHttpModule
	{
		/// <summary>
		/// 您将需要在您网站的 web.config 文件中配置此模块，
		/// 并向 IIS 注册此模块，然后才能使用。有关详细信息，
		/// 请参见下面的链接: http://go.microsoft.com/?linkid=8101007
		/// </summary>
		#region IHttpModule Members

		public void Dispose()
		{
			//此处放置清除代码。
		}

		public void Init(HttpApplication context)
		{
			//当 ASP.NET 获取与当前请求关联的当前状态（如会话状态）时
			context.AcquireRequestState += new EventHandler(OnAcquireRequestState);
		}

		#endregion

		/// <summary>
		/// 当 ASP.NET 获取与当前请求关联的当前状态（如会话状态）时,处理相关逻辑
		/// </summary>
		/// <param name="sender">当前Http上下文对象</param>
		/// <param name="e"></param>
		public void OnAcquireRequestState(Object sender, EventArgs e)
		{
			HttpContext context = ((HttpApplication)sender).Context;
			if (context.Handler == null) return;
			RequireLoginAttribute requireLoginAttribute;
			var attributes = Attribute.GetCustomAttributes(context.Handler.GetType(), true);
			if (attributes == null || attributes.Length == 0) return;
			foreach (var attribute in attributes)
			{
				requireLoginAttribute = attribute as RequireLoginAttribute;
				if (requireLoginAttribute != null && UserWeb.GetOnlineUser() == null)
				{
					UserWeb.RedirectToLoginPage();
				}
			}
		}
	}
}
